package com.sys.basics.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sys.basics.config.annotation.SysLogAnnotation;
import com.sys.basics.config.shiro.MyShiroRealm;
import com.sys.basics.entity.vo.UserOrgRoleVo;
import com.sys.basics.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import com.sys.basics.config.jsonRes.JsonResult;
import com.sys.basics.config.jsonRes.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.sys.basics.entity.SysUser;
import com.sys.basics.service.SysUserService;
import io.swagger.annotations.*;

import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.List;

/**
 * @author: ares
 * @date: 2021-09-30
 * @description: 用户管理 前端控制器
 */
@Validated
@Slf4j
@Api(tags = "用户管理")
@RestController
@RequestMapping("/basics/sysUser")
public class SysUserController extends AbstractController<SysUserService, SysUser> {

    @Autowired
    MyShiroRealm myShiroRealm;

    @Autowired
    SysUserService sysUserService;

    @SysLogAnnotation("查询当前登录用户包含角色信息和组织信息")
    @ApiOperation("查询当前登录用户包含角色信息和组织信息")
    @GetMapping("/getCurrentUserInfoWithRoleAndOrg")
    public JsonResult<SysUser> getCurrentUserInfoWithRoleAndOrg() {
        return result.success(sysUserService.getCurrentUserInfoWithRoleAndOrg(ShiroUtils.getUserId()));
    }

    @SysLogAnnotation("修改自己的密码")
    @ApiOperation("修改自己的密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPwd", required = true, value = "旧密码", paramType = "query"),
            @ApiImplicitParam(name = "newPwd", required = true, value = "新密码", paramType = "query")
    })
    @PutMapping("/modifySelfPwd")
    public JsonResult modifySelfPwd(@NotEmpty(message = "旧密码不能为空") String oldPwd,
                                    @NotEmpty(message = "新密码不能为空") String newPwd) {
        Long userId = ShiroUtils.getUserId();
        SysUser user = sysUserService.getById(userId);
        if(user == null){
            return result.error("用户不存在");
        }
        boolean modified = sysUserService.modifySelfPwd(user, oldPwd, newPwd);
        if (modified) {
            return result.success("修改成功");
        } else {
            return result.error("修改失败");
        }
    }

    @SysLogAnnotation("重置其他人密码")
    @ApiOperation("重置其他人密码")
    @ApiImplicitParam(name = "userId", required = true, value = "用户id", paramType = "query")
    @PutMapping("/resetSomeonePwd")
    public JsonResult resetSomeonePwd( @NotNull(message = "用户id不能为空") Long userId) {
        SysUser user = sysUserService.getById(userId);
        if(user == null){
            return result.error("用户不存在");
        }
        boolean modified = sysUserService.resetSomeonePwd(userId);
        if (modified) {
            return result.success("修改成功");
        } else {
            return result.error("修改失败");
        }
    }

    @SysLogAnnotation("切换默认组织")
    @ApiOperation("切换默认组织")
    @ApiImplicitParam(name = "orgId", value = "组织id", required = true, paramType = "query")
    @GetMapping("/changeCurrentUserOrg")
    public JsonResult changeCurrentUserOrg(@NotNull(message = "组织id不能为空") Long orgId) {
        SysUser userInfo = ShiroUtils.getUserInfo();
        boolean updated = sysUserService.updateUserDefaultOrg(userInfo.getId(), orgId);
        if(updated){
            userInfo.setDefaultOrgId(orgId);
            myShiroRealm.updateAuthenticationAndAuthorization(userInfo);
            result.success("切换组织成功");
        }else {
            result.error("切换组织失败");
        }
        return result;
    }

    @SysLogAnnotation("根据组织分页查询用户")
    @ApiOperation("根据组织分页查询用户")
    @ApiImplicitParam(name = "orgId", value = "组织id", required = true, paramType = "query")
    @PostMapping("/getPagesByOrg")
    public JsonResult<IPage<SysUser>> getPagesByOrg(@RequestBody PageParam<SysUser> param, @NotNull(message = "组织id不能为空") Long orgId) {
        JsonResult<IPage<SysUser>> returnPage = new JsonResult<IPage<SysUser>>();
        Page<SysUser> page = new Page<SysUser>(param.getPageNum(), param.getPageSize());
        IPage<SysUser> pageData = sysUserService.getPagesByOrg(page, orgId, param.getParam());
        return returnPage.success(pageData);
    }

    @SysLogAnnotation("批量更新用户状态")
    @ApiOperation("批量更新用户状态")
    @ApiImplicitParam(name = "status", value = "用户状态", required = true, paramType = "query")
    @PostMapping("/batchUpdateStatus")
    public JsonResult batchUpdateStatus(@RequestBody List<Long> userIds, @NotNull(message = "用户状态不能为空") Integer status) {
        int updated = sysUserService.batchUpdateStatus(userIds, status);
        if(updated == userIds.size()){
            result.success("批量更新用户状态成功");
        }else {
            result.error("批量更新用户状态失败");
        }
        return result;
    }

    @SysLogAnnotation("新建用户")
    @ApiOperation("新建用户")
    @PostMapping("/createUser")
    public JsonResult createUser(@RequestBody @Valid UserOrgRoleVo user) {
        if(user.getOrgIds().size() == 0 || user.getRoleIds().size() == 0) {
            return result.error("新建用户必须配置组织及角色！");
        }
        SysUser userByUsername = sysUserService.getByUsername(user.getUsername());
        if (userByUsername != null) {
            return result.error("账号已被使用！");
        }
        SysUser userByShortcode = sysUserService.getByShortcode(user.getShortcode());
        if(userByShortcode != null) {
            return result.error("短码已被使用！");
        }
        if (null != user) {
            int saveNum = sysUserService.createUserLinkOrgRole(user);
            if (saveNum>0) {
                result.success("添加用户成功");
            } else {
                result.error("添加用户失败！");
            }
        } else {
            result.error("请传入正确参数！");
        }
        return result;
    }

    @SysLogAnnotation("更新用户")
    @ApiOperation("更新用户")
    @PutMapping("/updateUser")
    public JsonResult updateUser(@RequestBody @Valid UserOrgRoleVo user) {
        if(user.getOrgIds().size() == 0 || user.getRoleIds().size() == 0) {
            return result.error("更新用户必须配置组织及角色！");
        }
        SysUser userById = sysUserService.getById(user.getId());
        if (userById == null) {
            return result.error("用户不存在！");
        }
        SysUser userByShortcode = sysUserService.getByShortcode(user.getShortcode());
        if(userByShortcode != null && !userByShortcode.getId().equals(user.getId()) ) {
            return result.error("短码已被使用！");
        }
        if (null != user) {
            int updateNum = sysUserService.updateUserLinkOrgRole(user, userById.getDefaultOrgId());
            if (updateNum>0) {
                result.success("修改用户成功");
            } else {
                result.error("修改用户失败！");
            }
        } else {
            result.error("请传入正确参数！");
        }
        return result;
    }
}
